- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathCoinChangeCoinRespect.java
43 lines (31 loc) Β· 748 Bytes
/
CoinChangeCoinRespect.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
packagesection12_Backtracking;
publicclassCoinChangeCoinRespect {
publicstaticvoidmain(String[] args) {
int[] denominations = { 2, 3, 5, 6 };
intamount = 10;
Stringans = "";
intcurrentCoinPosition = 0;
coinChange(denominations, amount, ans, currentCoinPosition);
}
staticvoidcoinChange(int[] coins, intamount, Stringans, intcoinIndex) {
if (amount < 0)
return;
if (amount == 0) {
System.out.println(ans);
return;
}
if (coinIndex > coins.length - 1)
return;
// include current coin
coinChange(coins, amount - coins[coinIndex], ans + coins[coinIndex], coinIndex);
// do not include current coin
coinChange(coins, amount, ans, coinIndex + 1);
}
}
/* output:
22222
2233
226
235
55
*/